package com.guang.springbootthread.test2;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Description 测试使用Future中的方法来进行取消
 * @Author liguang
 * @Date 2023/06/19/12:14
 */
public class NewCallablePro {

    private static class MyCallable implements Callable<Integer>{
        private int sum = 0;
        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程是："+Thread.currentThread().getName());
            for (int i = 0; i < 10000; i++) {
                if (Thread.currentThread().isInterrupted()){
                    System.out.println("如果检测到当前线程已经执行过期了，那么立即中断当前线程的执行，释放资源进行操作");
                    return null;
                }
                sum=sum+1;
            }
            return sum;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable myCallable = new MyCallable();
        // 包装成Runnable
        FutureTask<Integer> integerFutureTask = new FutureTask<>(myCallable);
        new Thread(integerFutureTask,"callableThread").start();
        Random random  = new Random();
        if (random.nextInt(100)>50){
            System.out.println("获取得到线程执行结果"+integerFutureTask.get());
        }else {
            // 超时执行，取消线程。非使用thread.interupt()，而是使用cancel
            integerFutureTask.cancel(true);
            // 调用获取得到结果，这里会报错
            // System.out.println("中断线程执行，打印结果看下："+integerFutureTask.get());
        }
    }
}
